package otxImporter;

import java.awt.Color;

public class OTXObjectThread extends Thread {

	private OTXImporter	importer;	//instance of importer for getting next pixels

	public OTXObjectThread(OTXImporter importer) {//constructor
		this.importer = importer;
	}

	@Override
	public void run() {
		int[] point;//x and y of the current scanning point
		boolean finished = false; //boolean for end detection

		int tileX, tileY, tileWidth, tileHeight;//values to find

		while (((point = this.importer.getNextPoint()) != null) && !finished) {
			Color c = new Color(this.importer.getImage().getRGB(point[0], point[1]));
			if (c.equals(OTXImporter.borderColor)) {//start horizontal check
				int x = point[0], y = point[1]; //saving positions of point
				tileX = x; //setting the x (same position of first borderColor point)
				tileY = y + 1; //setting the y (same position incremented by 1, not pointing to the border)
				while ((c = new Color(this.importer.getImage().getRGB(x, y))).equals(OTXImporter.borderColor)) {//getting the top border
					x++;
					this.importer.setPointChecked(x, y); //setting point as checked
				}
				x--;
				tileWidth = x - tileX; //setting tile width

				if (this.importer.startThread()) {
					finished = true;
				}

				while ((c = new Color(this.importer.getImage().getRGB(x, y))).equals(OTXImporter.borderColor)) {//getting the height
					y++;
					this.importer.setPointChecked(tileX - 1, x, y);//setting 
				}
				y--;
				tileHeight = y - tileY; //setting tile height

				int[] idState = this.importer.getIdAndState(new Color(this.importer.getImage().getRGB(tileX - 1, tileY - 1)));//retrieving tileID

				Object o = new Object();//creating object

				o.setTile(tileX, tileY, tileWidth, tileHeight, this.importer.getImage(), idState[0], idState[1]);//setting object values
				this.importer.addObject(o);//adding object to importer
			}
		}

		this.importer.setStopped();//blocks the current thread
	}
}
